package com.example.controller;

import com.example.common.Page;
import com.example.common.R;
import com.example.domain.Article;
import com.example.service.ArticleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/article")
@CrossOrigin("http://localhost:8080")
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @PostMapping
    @PreAuthorize("hasAuthority('article')")
    public R<String> add(@RequestBody Article article){
        articleService.add(article);
        return R.success("成功");
    }
    @PostMapping("/page")
    @PreAuthorize("hasAuthority('article')")
    public R<Page<List<Article>>> page(@RequestBody Page<Article> page){
        if (page.getPageNo() == null) page.setPageNo(0);
        if (page.getPageSize() == null) page.setPageSize(10);
        List<Article> list = articleService.page(page);
        Page<List<Article>> result = new Page<>();
        //对象拷贝
        BeanUtils.copyProperties(page,result,"data");
        result.setData(list);
        result.setSizeAll(articleService.cunt(page));
        return R.success(result);
    }
    @PutMapping
    @PreAuthorize("hasAuthority('article')")
    public R<String> update(@RequestBody Article article){
        articleService.update(article);
        return R.success("成功");
    }
    @GetMapping("/getOne/{id}")
    @PreAuthorize("hasAuthority('article')")
    public R<Article> getOne(@PathVariable String id){
        Article one = articleService.getOne(id);
        return R.success(one);
    }
    @DeleteMapping("/del/{id}")
    @PreAuthorize("hasAuthority('user')")
    public R<String> del(@PathVariable String id ){
        articleService.del(id);
        return R.success("删除成功");
    }
}
